package com.sanyue.codingsettlement.manager;

import com.sanyue.codingsettlement.common.ErrorCode;
import com.sanyue.codingsettlement.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 限流服务 ：RedissonLimiter
 * @author: Guan
 **/
@Service
public class RedisLimiterManager {

    @Resource
    private RedissonClient redissonClient;


    public static final String AI_LIMIT_KEY = "cs:ai:limit:userId:";


    /**
     * 执行限流操作
     */
    public void doLimit(Long userId){
        String key = AI_LIMIT_KEY + userId;
        // 获取限流器
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(key);

        // 初始化限流器
        // 1s最多执行俩次
        rateLimiter.trySetRate(RateType.OVERALL,10,1, RateIntervalUnit.DAYS);

        boolean res = rateLimiter.tryAcquire(1);
        if (!res) {
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST,"当天ai次数已用尽");
        }

    }
}
